package com.lg;

/**
 * Java三个线程依次序打印1-100
 * 同步块语法，java的同步块语法可以获取一个对象的锁使用
 * 
 * @author kaifa002
 *
 */
public class Main2 {
	public static void main(String[] args) {
		Task2 task = new Task2();
		
		Thread thread1 = new Thread(() -> task.print(1), "thread 1");
		Thread thread2 = new Thread(() -> task.print(2), "thread 2");
		Thread thread3 = new Thread(() -> task.print(0), "thread 3");

		thread1.start();
		thread2.start();
		thread3.start();
		
	}
}

class Task2 {
	private int count = 1;
	private static final Object LOCK = new Object();

	public void print(int id) {
		while (true) {
			synchronized (LOCK) {
				try {
					while (count % 3 != id) {
						LOCK.wait();
					}
					if (count > 100) {					
						break;
					}
					System.out.println(Thread.currentThread().getName() + ": " + count);
					count++;
					LOCK.notifyAll();
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
}
